package com.vf.cloud.common.controller;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.vf.cloud.common.util.R;
import com.vf.cloud.common.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@ControllerAdvice
public class FinalExceptionHandlerController implements ErrorController {

	@ExceptionHandler(value = Exception.class)
	public void error(HttpServletRequest request, HttpServletResponse response, Exception e) {
		
    	if(e instanceof JWTDecodeException) {
    		WebUtils.renderJson(response, R.failed(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "非法token.", e.getMessage()));
    	}
    	else if(e instanceof TokenExpiredException) {
    		WebUtils.renderJson(response, R.failed(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "会话过期，请重新登录.", e.getMessage()));
    	}
    	
    	else if(e instanceof org.springframework.web.bind.MissingServletRequestParameterException) {
    		WebUtils.renderJson(response, R.failed(500, "参数必填."));
    	}
    	else if (e instanceof HttpRequestMethodNotSupportedException) {
 			WebUtils.renderJson(response, R.failed(500, e.getMessage()));
 		}
    	else {
    		// 错误处理逻辑
    		int status = response.getStatus();
    		if (status == 404) {
    			WebUtils.renderJson(response, R.failed(404, "小伙子你有点调皮哦！(*^▽^*)"));
    		} else if (status == 500) {
    			WebUtils.renderJson(response, R.failed(500, "小伙子你麻烦大了！(*^▽^*)"));
    		} else if (status >= 100 && status < 200) {
    			WebUtils.renderJson(response, R.failed(500, "未知！"));
    		} else if (status >= 300 && status < 400) {
    			WebUtils.renderJson(response, R.failed(500, "重定向异常！"));
    		} else if (status >= 400 && status < 500) {
    			WebUtils.renderJson(response, R.failed(400, "请求错误!"));
    		} else if (status >= 400 && status < 500) {
    			WebUtils.renderJson(response, R.failed(400, "请求错误!"));
    		} else {
    			e.printStackTrace();
    			WebUtils.renderJson(response, R.failed(500, "小伙子你麻烦大了！(*^▽^*)"));
    		}
    	}
		
	}

}
